package cm.mefobe.android.telecomcost.activities;

import java.util.ArrayList;
import java.util.Calendar;

import cm.mefobe.android.telecomcost.R;
import cm.mefobe.android.telecomcost.DatabaseManager;
import cm.mefobe.android.telecomcost.TelecomCost;
import cm.mefobe.android.telecomcost.Utility;
import cm.mefobe.android.telecomcost.dialog.WeeklyThresholdDialog;
import cm.mefobe.android.telecomcost.entities.DayRange;
import cm.mefobe.android.telecomcost.entities.DayRangeThreshold;
import cm.mefobe.android.telecomcost.entities.MonthlyThreshold;
import cm.mefobe.android.telecomcost.entities.WeeklyThreshold;
import cm.mefobe.android.telecomcost.view.MonthlyThresholdEditView;
import cm.mefobe.android.telecomcost.view.WeeklyThresholdEditView;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class WeeklyThresholdListActivity extends TelecomcostActivity {

	private MonthlyThresholdEditView threshold_list;
	private DatabaseManager db;
	private ArrayList<MonthlyThreshold> monthly_thresholds;
	private Spinner monthly_threshold_list;
	private MonthlyThreshold currentMonth;
	private int currentWeek = -1;
	private ArrayList<WeeklyThreshold> thresholds;

	public ArrayList<WeeklyThreshold> getThresholds() {
		return thresholds;
	}

	public void setThresholds(ArrayList<WeeklyThreshold> thresholds) {
		this.thresholds = thresholds;
	}

	public static final int DIALOG_NEW_THRESHOLD = 1;

	public Dialog onCreateDialog(int id) {
		Log.i("WeeklyThresholdListActivity", "Creating dialog ohne bundle");
		Dialog dialog = null;
		switch (id) {
		case DIALOG_NEW_THRESHOLD:
			dialog = new WeeklyThresholdDialog(WeeklyThresholdListActivity.this);
			break;
		default:
			dialog = null;
		}

		return dialog;
	}

	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		Log.i("WeeklyThresholdListActivity", "Creating dialog with bundle");
		Dialog dialog = null;
		switch (id) {
		case DIALOG_NEW_THRESHOLD:
			dialog = new WeeklyThresholdDialog(WeeklyThresholdListActivity.this);
			break;
		default:
			dialog = null;
		}

		return dialog;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
		Log.i("WeeklyThresholdListActivity", "Preparing dialog with bundle");
		super.onPrepareDialog(id, dialog, args);
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		Log.i("WeeklyThresholdListActivity", "Preparing dialog ohne bundle");
		super.onPrepareDialog(id, dialog);
		Utility.setDialogLayout(dialog, LayoutParams.WRAP_CONTENT, 99);
	}

	/*
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.i("WeeklyThresholdListActivity", "Creating the activity");

		super.onCreate(savedInstanceState);
		db = TelecomCost.getDatabaseManager();

		setContentView(R.layout.monthly_threshold_view);

		threshold_list = (MonthlyThresholdEditView) findViewById(R.id.listViewThreshold);
		monthly_threshold_list = (Spinner) findViewById(R.id.spinnerMonths);
		monthly_threshold_list
				.setOnItemSelectedListener(new OnItemSelectedListener() {

					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						setMonth(arg2);
					}

					public void onNothingSelected(AdapterView<?> arg0) {
					}
				});
	}

	protected void setMonth(int index) {
		currentMonth = monthly_thresholds.get(index);
		bindThresholds();
	}

	public int getWeek() {
		return currentWeek;
	}

	public MonthlyThreshold getMonthlyThreshold() {
		return currentMonth;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		Log.i("WeeklyThresholdListActivity",
				"creating options menu for providers : ");
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_save, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.i("WeeklyThresholdListActivity", "onOptionsItemSelected");
		switch (item.getItemId()) {
		case R.id.itemSAve:
			// showDialog(DIALOG_NEW_THRESHOLD);
			saveWeeklyThresholds();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void saveWeeklyThresholds() {
		Log.i("WeeklyThresholdListActivity", "saving WeeklyThreshold...");		

		ArrayList<WeeklyThresholdEditView> views = threshold_list.getThresholdEditViews();
		//thresholds = new ArrayList<WeeklyThreshold>();
		int index = 0;
		double total = 0;
		while (index < views.size()) {
			WeeklyThreshold threshold = views.get(
					index).getWeeklyThreshold();			
			DayRangeThreshold range = new DayRangeThreshold(threshold.getAmount(),new DayRange(threshold.getWeek().getFirstDay(),threshold.getWeek().getLastDay()));
			db.saveDayRangeThreshold(range,null,null);
			db.saveWeeklyThreshold(threshold);
			total = total + threshold.getAmount();
			index++;
		}	
		
		Log.i("WeeklyThresholdDialog", "saving monthly threshold......old amount = " + currentMonth.getAmount() + "...new amount = " + total);
		currentMonth.setAmount(total);
		db.saveMonthlyThreshold(currentMonth,null,null);		
		Log.i("WeeklyThresholdDialog", "weekly threshold saved...");
		Toast.makeText(WeeklyThresholdListActivity.this, "Weekly threshold saved !!!", 3).show();
		restart();
	}

	private void restart() {
		Intent intent = new Intent().setClass(WeeklyThresholdListActivity.this,
				WeeklyThresholdListActivity.class);
		startActivity(intent);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.i("WeeklyThresholdListActivity", "onActivityResult");
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onDestroy() {
		Log.i("WeeklyThresholdListActivity", "Destroying the activity");
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		Log.i("WeeklyThresholdListActivity", "Pausing the activity");
		super.onPause();
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		Log.i("WeeklyThresholdListActivity", "Postcreating the activity");
		super.onPostCreate(savedInstanceState);
	}

	@Override
	protected void onPostResume() {
		Log.i("WeeklyThresholdListActivity", "PostResuming the activity");
		super.onPostResume();
		bindData();
	}

	public void bindData() {
		bindMonthlyThresholds();
		selectCurrentMonth();
		bindThresholds();
	}

	@Override
	public void onAttachedToWindow() {
		super.onAttachedToWindow();
		Log.i("WeeklyThresholdListActivity",
				"activity has been attached to the window manager");
	}

	@Override
	protected void onRestart() {
		Log.i("WeeklyThresholdListActivity", "Restarting the activity");
		super.onRestart();
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		Log.i("WeeklyThresholdListActivity",
				"onRestoreInstanceState the activity");
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onResume() {
		Log.i("WeeklyThresholdListActivity", "Resuming the activity");
		super.onResume();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		Log.i("WeeklyThresholdListActivity", "onSaveInstanceState the activity");
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onStart() {
		Log.i("WeeklyThresholdListActivity", "Starting the activity");
		super.onStart();
	}

	@Override
	protected void onStop() {
		Log.i("WeeklyThresholdListActivity", "Stopping the activity");
		super.onStop();
	}

	public void bindThresholds() {
		if (currentMonth != null) {
			Log.i("WeeklyThresholdListActivity", "binding WeeklyThreshold...");
			threshold_list.setThreshold(currentMonth);			
		} else {
			Log.i("WeeklyThresholdListActivity",
					"cannot bind the weekly threshold...set the month and week first");
		}
	}

	public void bindMonthlyThresholds() {
		Log.i("WeeklyThresholdListActivity",
				currentMonth == null ? "binding MonthlyThreshold..."
						: "MonthlyThreshold already bound");
		monthly_thresholds = currentMonth == null ? db.getMonthlyThreshold()
				: monthly_thresholds;

		Log.i("WeeklyThresholdListActivity",
				"binding MonthlyThreshold to spinner...");

		ArrayAdapter<MonthlyThreshold> adapter = new ArrayAdapter<MonthlyThreshold>(
				WeeklyThresholdListActivity.this,
				android.R.layout.simple_spinner_item, monthly_thresholds);
		monthly_threshold_list.setAdapter(adapter);
	}

	private void selectCurrentMonth() {
		if (currentMonth == null) {
			Log.i("MonthlyThresholdListActivity", "selecting current month...");
			if (monthly_thresholds != null && monthly_thresholds.size() >= 12) {
				Calendar cal = Calendar.getInstance();
				int month = cal.get(Calendar.MONTH);

				int index = 0;
				while (index < monthly_thresholds.size()) {
					MonthlyThreshold threshold = monthly_thresholds.get(index);
					if (threshold.getMonth().getMonthOfYear() == month) {
						Log.i("MonthlyThresholdListActivity",
								"selecting current month..."
										+ threshold.getMonthNameLong());
						monthly_threshold_list.setSelection(index);
						return;
					}

					index++;
				}

				Log.i("MonthlyThresholdListActivity",
						"could not select the current month...");

			} else {
				Log.i("MonthlyThresholdListActivity",
						"cannot select current month...monthly_thresholds not loaded yet");
			}
		} else {
			Log.i("MonthlyThresholdListActivity",
					"current month already set...");
		}
	}

	@Override
	public String toString() {
		return "WeeklyThresholdListActivity";
	}

	public void setMonthlyThreshold(MonthlyThreshold threshold)
			throws Exception {
		if (monthly_thresholds != null) {
			Log.i("WeeklyThresholdListActivity",
					"updating MonthlyThreshold in list activity...");
			int index = 0;
			while (index < monthly_thresholds.size()) {
				MonthlyThreshold _threshold = monthly_thresholds.get(index);
				if (_threshold.getMonth() == threshold.getMonth()) {
					_threshold = threshold;
					return;
				}

				index++;
			}
		}

		throw new Exception(
				"could not set the monthly threshold...does not exist in the list");
	}
}
